/*
 * $RCSfile: Webcat.java,v $$
 * $Revision: 1.1 $
 * $Date: 2014-03-19 $
 *
 * Copyright (C) 2008 Skin, Inc. All rights reserved.
 *
 * This software is the proprietary information of Skin, Inc.
 * Use is subject to license terms.
 */
package com.skin.webcat.util;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.skin.webcat.datasource.ConnectionManager;

/**
 * <p>Title: Webcat</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2006</p>
 * @author xuesong.net
 * @version 1.0
 */
public class Webcat {
    private static Logger logger = LoggerFactory.getLogger(Webcat.class);

    /**
     * @return List<String>
     */
    public static List<String> getConnectionList() {
        return ConnectionManager.getConfigNameList();
    }

    /**
     * @param name
     * @return Connection
     * @throws SQLException
     */
    public static Connection getConnection(String name) throws SQLException {
        return ConnectionManager.getConnection(name);
    }

    /**
     * @param name
     * @param database
     * @return Connection
     * @throws SQLException
     */
    public static Connection getConnection(String name, String database) throws SQLException {
        return ConnectionManager.getConnection(name, database);
    }

    /**
     * @param filePath
     * @return String
     */
    public static String getSource(String filePath) {
        try {
            if(filePath.endsWith(".link.sql")) {
                String content = IO.read(new File(filePath), "UTF-8");
                String[] list = content.split("\\n");
                StringBuilder buffer = new StringBuilder();
    
                for(String line : list) {
                    line = line.trim();
    
                    if(line.startsWith("#")) {
                        continue;
                    }

                    if(line.endsWith(".sql")) {
                        String sql = IO.read(new File(line), "UTF-8");
                        buffer.append(sql);
                    }
                }
                return buffer.toString();
            }
            else if(filePath.endsWith(".sql")) {
                return IO.read(new File(filePath), "UTF-8");
            }
            else {
                return "";
            }
        }
        catch(IOException e) {
            logger.warn(e.getMessage(), e);
        }
        return "";
    }
}
